var db = wx.cloud.database({
  env: 'supersup-2b4d39'
})

const rootUrl = 'https://www.proke.top/common/smartCarWashing/'
const carWashingUrl = "https://www.proke.top/carwashing/"
export const smsSend = {
  post(model, success, fail) {
    commonPost("https://www.proke.top/common/commonService/" + 'sMSSend/aliSMSSend', model, success, fail)
  }
}

export const robot_data = {
  get:function(model, success, fail){
    commonGet(rootUrl + 'ws/page',model, success, fail)
  },
}

export const sendToRobot = {
  post(model, success, fail) {
    commonPost(carWashingUrl + "DownData", model, success, fail)
  }
}

function commonGet(url,model,success,fail){
  wx.request({
    url: url,
    data: model,
    method: 'get',
    header: { 'Content-Type': 'application/json' },
    success: function (res) {
      if (res.data.errorcode == 1) {
        //根据时间插入对象
        if (success != null) { success(res.data.data.content,res) }
      } else {
        if (fail != null) { fail(res.data.message) }
      }
    },
    fail: function () {
      if (fail != null) { fail("未知错误") }
    }
  })
}
function commonPost(url, model, success, fail) {
  wx.request({
    url: url,
    data: model,
    method: 'post',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      if (res.data.errorcode == 1) {
        //根据时间插入对象
        if (success != null) {
          success(res)
        }
      } else {
        if (fail != null) {
          fail(res.data.message)
        }
      }
    },
    fail: function () {
      if (fail != null) {
        fail("未知错误")
      }
    }
  })
}

function getHistory(count, tmpArr,dbName,orderName,orderWay,whereDic,successFunc) {
  var func = null
  if (count == 0) {
    func = db.collection(dbName)
      .limit(20).where(whereDic).orderBy(orderName, orderWay)
  } else {
    func = db.collection(dbName)
      .skip(count)
      .limit(20).where(whereDic).orderBy(orderName, orderWay)
  }
  //获取单位信息
  func.get({
    success: function (res) {
      if (res.data.length != 0) {
        tmpArr = tmpArr.concat(res.data)
        count += 20
        getHistory(count, tmpArr,dbName,orderName,orderWay,whereDic,successFunc)
      } else {
        successFunc(tmpArr)
      }
    }
  })
}

module.exports = {
  db: db,
  smsSend: smsSend,
  sendToRobot: sendToRobot,
  robot_data:robot_data,
  getHistory:getHistory
}